#
# This file is a part of the open-eBackup project.
# This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
# If a copy of the MPL was not distributed with this file, You can obtain one at
# http://mozilla.org/MPL/2.0/.
#
# Copyright (c) [2024] Huawei Technologies Co.,Ltd.
#
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
#

import os
import stat

from dws.commons.common import log
from common.common import is_clone_file_system
from dws.commons.const import PERMISSION_644
from dws.restore.pre_job_parent import RestorePreJob
from common.file_common import change_path_permission, exec_lchown_dir_recursively


class ArchiveTapePreJob(RestorePreJob):
    def __init__(self, parse_restore_param_obj, pid):
        super().__init__(parse_restore_param_obj, pid)

    def do_pre_job(self):
        """
        磁带副本恢复流程：1. 通用备份副本恢复前置任务流程  2. 磁带特殊处理流程
        """
        # 通用流程
        if not self._do_common_pre_job():
            log.error(f"Failed to do common pre job.")
            return False
        if not is_clone_file_system(self._parse_restore_param_obj.get_restore_param()):
            return True
        # 归档到磁带的副本恢复特有流程: 修改映射文件目录权限
        metadata_path, _ = self._parse_restore_param_obj.get_available_path()
        if not metadata_path:
            log.error(f"No cache/metadata path can be read or written."
                      f"metadata_path:{metadata_path}, main task:{self._main_job_id}")
            return False
        temp_download_path = os.path.join(metadata_path, "meta",
                                          self._parse_restore_param_obj.get_copy_id(), "archiveDownload")
        log.debug(f"Download path: {temp_download_path}")
        dir_mode = stat.S_IRWXU | stat.S_IRGRP | stat.S_IXGRP | stat.S_IROTH | stat.S_IXOTH
        change_path_permission(metadata_path, mode=dir_mode)
        change_path_permission(os.path.join(metadata_path, "meta"), mode=dir_mode)
        change_path_permission(os.path.join(metadata_path, "meta", self._parse_restore_param_obj.get_copy_id()), \
                               mode=dir_mode)
        change_path_permission(temp_download_path, mode=dir_mode)
        change_path_permission(os.path.join(temp_download_path, "filesystemRelationship.txt"), mode=PERMISSION_644)
        if not exec_lchown_dir_recursively(metadata_path, "root", "rdadmin"):
            log.error(f"Fail to change owner for {metadata_path}.  main task:{self._main_job_id}")
            return False
        # 修改数据目录权限
        all_data_path = self._parse_restore_param_obj.get_all_data_repo_path()
        log.debug(f"All data path: {all_data_path}")
        for data_path in all_data_path:
            change_path_permission(os.path.join(data_path, "data"), mode=dir_mode)
        log.info("Update privilege successfully.")
        return True
